package com.ev.k3cloudBusiness.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ev.custom.dao.DictionaryDao;
import com.ev.custom.domain.DictionaryDO;
import com.ev.framework.utils.R;
import com.ev.hr.dao.EmployeeInfoDao;
import com.ev.hr.domain.EmployeeInfoDO;
import com.ev.hr.service.EmployeeInfoService;
import com.ev.k3cloud.entity.K3CloudBillQueryEntity;
import com.ev.k3cloud.enums.K3CloudBaseFormId;
import com.ev.k3cloud.service.K3CloudService;
import com.ev.k3cloud.service.kingdeeMiddlewareService;
import com.ev.k3cloudBusiness.service.K3EmpInfoSynService;
import com.ev.k3cloudBusiness.vo.K3EmpInfoResultsVo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class K3EmpInfoSynServiceImpl implements K3EmpInfoSynService {
    private static final String EMPLOYEE_STATUS = "employee_status";
    private static final String EMPLOYMENT_TYPE = "employment_type";
    @Autowired
    EmployeeInfoDao employeeInfoDao;
    @Autowired
    K3CloudService k3CloudService;
    @Autowired
    EmployeeInfoService employeeInfoService;
    @Autowired
    DictionaryDao dictionaryDao;
    @Autowired
    kingdeeMiddlewareService kingdeeMiddlewareService;
    @Override
    public R EmpInfoSyn() throws Exception {
        // 获取本地所有的用工类型、用工状态
        List<DictionaryDO> localEmployStatusList = dictionaryDao.listByType(EMPLOYEE_STATUS);
        List<DictionaryDO> localEmployTypeList = dictionaryDao.listByType(EMPLOYMENT_TYPE);
        //查询芯软云员工
        List<EmployeeInfoDO> employeeInfoDaoList=employeeInfoService.listAll();
        //调用K3Cloud员工单据查询接口查询启用的员工

        String materialResult=kingdeeMiddlewareService.EmpAll();
        JSONObject resultObj = JSON.parseObject(materialResult);
        if(!resultObj.getString("code").equals("0"))
        {
            log.info(resultObj.getString("msg"));
            return  R.error(resultObj.getString("msg"));
        }
        JSONArray data=JSON.parseArray(resultObj.get("data").toString());
        List<K3EmpInfoResultsVo> empInfoResultsVoList=new ArrayList<>();
        for (int i=0;i<data.size();i++)
        {
            JSONObject Obj=data.getJSONObject(i);
            K3EmpInfoResultsVo empInfoResultsVo= new K3EmpInfoResultsVo();
            empInfoResultsVo.setFID(Obj.getLong("id"));
            empInfoResultsVo.setFNAME(Obj.getString("name"));
            empInfoResultsVo.setFNUMBER(Obj.getString("number"));

            empInfoResultsVoList.add(empInfoResultsVo);
        }
        if(empInfoResultsVoList.size() > 0)
        {
            // 本地职员代码
            List<Long> localIdList = employeeInfoDaoList.stream().map(EmployeeInfoDO::getId).collect(Collectors.toList());
            // K3Cloud员工代码
            List<Long> remoteIdList = empInfoResultsVoList.stream().map(K3EmpInfoResultsVo::getFID).collect(Collectors.toList());
            // 删除的 k3无，本地有
            List<Long> deleteIdList = localIdList.stream().filter(e -> !remoteIdList.contains(e)).collect(Collectors.toList());
            // 修改的（本地库有的，远端库有的）
            List<Long> updateIdList = remoteIdList.stream().filter(localIdList::contains).collect(Collectors.toList());
            // 新增的（本地库无的，远端库有的）
            remoteIdList.removeAll(updateIdList);
            if(deleteIdList.size()>0)
            {
                //批量删除
                List<EmployeeInfoDO> employeeInfoDOS=employeeInfoDaoList.stream().filter(e->deleteIdList.contains(e.getId())).collect(Collectors.toList());
                for (EmployeeInfoDO employeeInfoDO:employeeInfoDOS
                ) {
                    employeeInfoDO.setDelFlag(1);
                }
                employeeInfoService.batchUpdate(employeeInfoDOS);
                log.info("批量删除");
            }
            if(updateIdList.size()>0)
            {
                //批量更新
                List<K3EmpInfoResultsVo> employeeInfoDOList = empInfoResultsVoList.stream().filter(e -> updateIdList.contains(e.getFID())).collect(Collectors.toList());
                List<EmployeeInfoDO> employeeInfoLstUpdate=employeeInfoDaoList.stream().filter(e->updateIdList.contains(e.getId())).collect(Collectors.toList());
                K3EmpInfoResultsVo empInfoResultsVo;
                for (EmployeeInfoDO employeeInfoDO:employeeInfoLstUpdate
                ) {
                    empInfoResultsVo=employeeInfoDOList.stream().filter(e->(employeeInfoDO.getId().equals(e.getFID()))).collect(Collectors.toList()).get(0);
                    //员工名称
                    employeeInfoDO.setEmployeeName(empInfoResultsVo.getFNAME());
                    //员工代码
                    employeeInfoDO.setEmployeeCode(empInfoResultsVo.getFNUMBER());

                    employeeInfoDO.setDelFlag(0);
                }
                employeeInfoService.batchUpdate(employeeInfoLstUpdate);
                log.info("批量更新");
            }
            if(remoteIdList.size()>0)
            {
                //批量插入
                List<K3EmpInfoResultsVo> empInfoResultsVos= empInfoResultsVoList.stream().filter(e -> remoteIdList.contains(e.getFID())).collect(Collectors.toList());
                List<EmployeeInfoDO> employeeInfoDOS= Lists.newArrayList();
                List<DictionaryDO> employStatusDictionarDo=localEmployStatusList.stream().filter(e-> e.getName().equals("在职")).collect(Collectors.toList());
                List<DictionaryDO> employTypeDictionarDo=localEmployTypeList.stream().filter(e-> e.getName().equals("劳动合同")).collect(Collectors.toList());
                if(employStatusDictionarDo.size()==0)
                {
                    return  R.error("用工状态--在职不存在");
                }
                if(employTypeDictionarDo.size()==0)
                {
                    return  R.error("用工类型--劳动合同不存在");
                }
                for (K3EmpInfoResultsVo empInfoResultsVo:empInfoResultsVos
                ) {
                    EmployeeInfoDO employeeInfoDO=new EmployeeInfoDO();
                    employeeInfoDO.setId(empInfoResultsVo.getFID());
                    //员工姓名
                    employeeInfoDO.setEmployeeName(empInfoResultsVo.getFNAME());
                    //员工代码
                    employeeInfoDO.setEmployeeCode(empInfoResultsVo.getFNUMBER());

                    employeeInfoDO.setDelFlag(0);
                    employeeInfoDO.setEmploymentState(employStatusDictionarDo.get(0).getId());
                    employeeInfoDO.setEmploymentType(employTypeDictionarDo.get(0).getId());
                    employeeInfoDOS.add(employeeInfoDO);
                }
                employeeInfoService.batchSave(employeeInfoDOS);
                log.info("批量新增");
            }
        }
        return R.ok();
    }
}
